from django.views import View
from app001.models import Task
from lib.common import CommonResponse
from lib.handle_request import handle_request
import uuid


class DataToolsMixin:
    @staticmethod
    def _task_data(task):
        task_id = task.pk
        task_uid = str(task.task_uid)
        task_name = task.task_name
        task_time = str(task.task_time)
        task_desc = task.task_desc
        return {
            'task_id': task_id,
            'task_uid': task_uid,
            'task_name': task_name,
            'task_time': task_time,
            'task_desc': task_desc,
        }

    @staticmethod
    def _get_data_from_request(data):
        task_name = data.get('task_name')
        task_desc = data.get('task_desc')
        return task_name, task_desc


class TaskCRView(View, DataToolsMixin):
    def get(self, request):
        data = []
        task_all = Task.objects.all()
        for task in task_all:
            data_dict = self._task_data(task)
            data.append(data_dict)
        return CommonResponse(code=100, msg='查询所有成功', task_list=data)

    @handle_request
    def post(self, request):
        data = request.data
        task_uid = uuid.uuid4()
        if not data:
            return CommonResponse(code=102, msg='请补齐参数')
        task_obj = Task.objects.create(task_uid=task_uid, **data)
        task = self._task_data(task_obj)
        return CommonResponse(code=100, msg='添加成功', task=task)


class TaskRUDView(View, DataToolsMixin):

    def get(self, request, tid):
        task = Task.objects.filter(pk=tid).first()
        if not task:
            return CommonResponse(code=103, msg='当前任务不存在')
        data = self._task_data(task)
        return CommonResponse(code=100, msg='查询成功', task=data)

    @handle_request
    def put(self, request, tid):
        data = request.data
        if not data:
            return CommonResponse(code=101, msg='数据为空')
        task = Task.objects.filter(pk=tid)
        if not task:
            return CommonResponse(code=103, msg='当前任务不存在')
        task.update(**data)
        data_obj = self._task_data(task.first())
        return CommonResponse(code=100, msg=f'更新任务成功', task=data_obj)

    def delete(self, request, tid):
        Task.objects.filter(pk=tid).delete()
        return CommonResponse(code=100, msg='删除任务成功')
